package com.mifengs.mall.adapter;

import android.content.Context;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.R;
import com.mifengs.mall.entity.GoodsBean;
import com.mifengs.mall.entity.NoticeBean;
import com.mifengs.mall.util.ImageLoadUtil;
import com.mifengs.mall.util.ToIntentUtil;
import com.mifengs.mall.widget.ADTextView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lihaoqi on 2017/11/1.
 */

public class HomeMidAdapter extends  DelegateAdapter.Adapter<RecyclerView.ViewHolder> {


    private final Timer mTimer;
    private Context mContext;

    private Map<String,Object> datas = new HashMap<>();
    private MyHandler mHandler;
    private TimerTask mTimerTask;
    private MyListener mListener01,mListener02,mListener03;

    public HomeMidAdapter(Context mContext) {
        this.mContext = mContext;
        mTimer = new Timer();
    }

    public void setDatas(Map<String, Object> datas) {
        this.datas = datas;
        notifyDataSetChanged();
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return new LinearLayoutHelper();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MidViewHolder(LayoutInflater.from(mContext).inflate(R.layout.fragment_home_mid,parent,false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if(holder instanceof MidViewHolder){
            MidViewHolder viewHolder = (MidViewHolder)holder;
            if(datas.get("qgUrl")!=null){
//                viewHolder.vEnter.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        ToIntentUtil.toCommonIntent((String) datas.get("qgUrl"),mContext);
//                    }
//                });
            }
            viewHolder.mImg.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            viewHolder.aDTextView.setSpeed(3);
            viewHolder.aDTextView.setInterval(1500);

            if(datas.get("bgImg")!=null){
                String bgImg = (String) datas.get("bgImg");
                String photoUrl = PreferenceUtils.getPhotoPath(mContext);
                String totalUrl = photoUrl+bgImg;
                Glide.with(mContext.getApplicationContext())
                        .load(totalUrl)
                        .diskCacheStrategy(DiskCacheStrategy.RESULT)
                        .placeholder(R.drawable.home_mid_bg)
                        .error(R.drawable.home_mid_bg)
                        .into(viewHolder.ivBg);
//                Glide.with(mContext.getApplicationContext())
//                        .load("")
//                        .diskCacheStrategy(DiskCacheStrategy.RESULT)
//                        .placeholder(R.drawable.test_bg)
//                        .error(R.drawable.test_bg)
//                        .into(viewHolder.ivBg);
//
            }

            if(datas.get("notices")!=null){
                viewHolder.aDTextView.setTexts((List<NoticeBean>) datas.get("notices"));
                viewHolder.aDTextView.setOnItemClickListener(new ADTextView.OnItemClickListener() {
                    @Override
                    public void onClick(String url) {
                        ToIntentUtil.toCommonIntent(url,mContext);
                    }
                });
                viewHolder.llMoreView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(datas.get("moreNoticeUrl")!=null){
                            ToIntentUtil.toCommonIntent((String) datas.get("moreNoticeUrl"),mContext);
                        }
                    }
                });
            }
            if(datas.get("topGoods")!=null){
                List<GoodsBean> beanList = (List<GoodsBean>) datas.get("topGoods");
                if(beanList.size()>0){
                    final GoodsBean beanfirst = beanList.get(0);
                    ImageLoadUtil.displayImage(mContext,beanfirst.getImg(),viewHolder.mImg);
                    viewHolder.mTvYuanJiao.setText("¥"+beanfirst.getOriginalCost());
                    viewHolder.mTvXianJiao.setText("¥"+beanfirst.getDiscountPrice());
                    viewHolder.mTvYuanJiao.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
                    viewHolder.mLlHot.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ToIntentUtil.toCommonIntent(beanfirst.getActionUrl(),mContext);
                        }
                    });
                    if(beanList.size()>5){
                        viewHolder.mRvTopList.setLayoutManager(new GridLayoutManager(mContext,4));
                        final List<GoodsBean> beanListTop = beanList.subList(1,5);
                        MidTopListAdapter midTopListAdapter = new MidTopListAdapter(beanListTop);
                        viewHolder.mRvTopList.setAdapter(midTopListAdapter);
                        midTopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                ToIntentUtil.toCommonIntent(beanListTop.get(position).getActionUrl(),mContext);
                            }
                        });
//                        beanList.removeAll(beanList.subList(0,4));
                        viewHolder.mRvBottomList.setLayoutManager(new GridLayoutManager(mContext,4));
                        final List<GoodsBean> beanBottomTop = beanList.subList(5,beanList.size());
                        MidTopListAdapter midBottomListAdapter = new MidTopListAdapter(beanBottomTop);
                        viewHolder.mRvBottomList.setAdapter(midBottomListAdapter);
                        midBottomListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                ToIntentUtil.toCommonIntent(beanBottomTop.get(position).getActionUrl(),mContext);
                            }
                        });
                    }else{
                        viewHolder.mRvTopList.setLayoutManager(new GridLayoutManager(mContext,4));
                        final List<GoodsBean> beanListTop = beanList.subList(1,beanList.size());
                        MidTopListAdapter midTopListAdapter = new MidTopListAdapter(beanListTop);
                        viewHolder.mRvTopList.setAdapter(midTopListAdapter);
                        midTopListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                            @Override
                            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                ToIntentUtil.toCommonIntent(beanListTop.get(position).getActionUrl(),mContext);
                            }
                        });

                        viewHolder.mRvBottomList.setLayoutManager(new GridLayoutManager(mContext,4));
                        List<GoodsBean> beanBottomTop = new ArrayList<>();
                        MidTopListAdapter midBottomListAdapter = new MidTopListAdapter(beanBottomTop);
                        viewHolder.mRvBottomList.setAdapter(midBottomListAdapter);
                    }
                }

            }
        }
    }

    private void setBaokuanView(GoodsBean goodsBean) {

    }

    private void setListener(List<GoodsBean> beanList, LinearLayout topGoodsView, int i) {
        switch (i){
            case 0:
                mListener01 = new MyListener(beanList.get(i));
                topGoodsView.getChildAt(i).setOnClickListener(mListener01);
                break;
            case 1:
                mListener02 = new MyListener(beanList.get(i));
                topGoodsView.getChildAt(i).setOnClickListener(mListener02);
                break;
            case 2:
                mListener03 = new MyListener(beanList.get(i));
                topGoodsView.getChildAt(i).setOnClickListener(mListener03);
                break;
        }
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    public class MidViewHolder extends RecyclerView.ViewHolder{

        private ADTextView aDTextView;
       // private LinearLayout topGoodsView;
        private LinearLayout llMoreView;
       // private View vEnter;
        private ImageView ivBg;
        private RecyclerView mRvTopList;
        private RecyclerView mRvBottomList;
        private ImageView mImg;
        private TextView mTvXianJiao;
        private TextView mTvYuanJiao;
        private LinearLayout mLlHot;

        public MidViewHolder(View itemView) {
            super(itemView);
            aDTextView = itemView.findViewById(R.id.adtextView);
            //topGoodsView = itemView.findViewById(R.id.ll_top_goods);
            llMoreView = itemView.findViewById(R.id.ll_more);
            //vEnter = itemView.findViewById(R.id.v_enter);
            ivBg = itemView.findViewById(R.id.iv_bg);
            mRvTopList = itemView.findViewById(R.id.rv_top_list);
            mRvBottomList = itemView.findViewById(R.id.rv_bottom_list);
            mImg = itemView.findViewById(R.id.iv_img);
            mTvXianJiao = itemView.findViewById(R.id.tv_xianjia);
            mTvYuanJiao = itemView.findViewById(R.id.tv_yuanjia);
            mLlHot = itemView.findViewById(R.id.ll_hot);
        }
    }


    private void setTopGoods(GoodsBean bean, FrameLayout layout){
        LinearLayout ll01 = (LinearLayout)layout.getChildAt(0);
        FrameLayout fl = (FrameLayout) ll01.getChildAt(0);
        ImageView ivImg = (ImageView) fl.getChildAt(0);
        TextView tvDiscount = (TextView) fl.getChildAt(1);
        TextView tvName = (TextView)ll01.getChildAt(1);
        TextView tvXianjia = (TextView)ll01.getChildAt(2);
        TextView tvYuanjia = (TextView)ll01.getChildAt(3);
        ImageLoadUtil.displayImage(mContext,bean.getImg(),ivImg);
        double discount = Double.parseDouble(bean.getDiscount())*10;
        tvDiscount.setText(discount+"折");
        tvName.setText(bean.getGoodName());
        tvXianjia.setText("¥"+bean.getDiscountPrice());
        tvYuanjia.setText("¥"+bean.getOriginalCost());
        tvYuanjia.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        tvYuanjia.getPaint().setAntiAlias(true);
    }

    private void setCountDownTime(List<GoodsBean> beanList, LinearLayout layout){
        for(int i=0;i<beanList.size();i++){
            GoodsBean bean = beanList.get(i);
            FrameLayout fl = (FrameLayout) layout.getChildAt(i);
            LinearLayout ll02 = (LinearLayout)fl.getChildAt(1);
            TextView tvCountDownTime = (TextView)ll02.getChildAt(0);
            String time = calculateText(bean.getEndTime());
            tvCountDownTime.setText(time);
            if(i==2) break;
        }
    }


    private String calculateText(String time){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date=sdf.parse(time);
            long  s1= date.getTime();
            long  s2= System.currentTimeMillis();//得到当前的毫秒
            long minusTime = s1 -s2;
            if(minusTime>0){
                int  day= (int) (minusTime/1000/60/60/24);
                long dayTime = day*60L*60*24*1000;
                long minusDay = minusTime - dayTime;
                int hour = (int) (minusDay/1000/60/60);
                long minusHour = minusDay - (hour*60L*60*1000);
                int minute = (int) (minusHour/1000/60);
                long minusMinute = minusHour - (minute*1000L*60);
                int second = (int) (minusMinute/1000);
                String sHour,sMinute,sSecond;
                sHour = hour<10?"0"+hour:""+hour;
                sMinute = minute<10?"0"+minute:""+minute;
                sSecond = second<10?"0"+second:""+second;
                return day+"天 "+sHour+":"+sMinute+":"+sSecond ;
            }else{
                return "已结束";
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }
    }

    public void release(){
        if(mTimer!=null){
            mTimer.cancel();
        }
    }

    class MyHandler extends Handler{

        private List<GoodsBean> beanList;
        private LinearLayout layout;

        public MyHandler(List<GoodsBean> beanList, LinearLayout layout) {
            this.beanList = beanList;
            this.layout = layout;
        }

        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case 1:
                    setCountDownTime(beanList,layout);
                    break;
            }
        }
    }

    class MyListener implements View.OnClickListener{

        private GoodsBean bean;

        public MyListener(GoodsBean bean) {
            this.bean = bean;
        }

        @Override
        public void onClick(View v) {
            ToIntentUtil.toCommonIntent(bean.getActionUrl(),mContext);
        }
    }

}
